package com.gxh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gxh.Websocket.WebSocketServer;
import com.gxh.context.BaseContext;
import com.gxh.dto.RequestMachinePageQueryDTO;
import com.gxh.dto.UploadMachinePageQueryDTO;
import com.gxh.dto.UserMachineDTO;
import com.gxh.dto.UserRequestMachineDTO;
import com.gxh.entity.*;
import com.gxh.mapper.*;
import com.gxh.result.PageResult;
import com.gxh.service.UserMachineService;
import com.gxh.utils.AliOssUtil;
import com.gxh.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserMachineServiceImpl implements UserMachineService {

    @Autowired
    private UserMachineMapper userMachineMapper;
    @Autowired
    private UserMachineImageMapper userMachineImageMapper;
    @Autowired
    private UserMachineVideoMapper userMachineVideoMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserRequestMachineMapper userRequestMachineMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 上传设备信息
     * @param userMachineDTO
     */
    @Transactional
    public void upload(UserMachineDTO userMachineDTO) {
        UserMachine userMachine = new UserMachine();
        BeanUtils.copyProperties(userMachineDTO,userMachine);
        userMachine.setStatus(0);
        userMachine.setCreateUser(BaseContext.getCurrentId());
        userMachine.setCreateTime(LocalDateTime.now());
        userMachineMapper.insert(userMachine);
        //判断是否有图片信息
        List<UserMachineImage> images = userMachineDTO.getImages();
        if (images != null && !images.isEmpty()) {
            //插入图片信息
            for (UserMachineImage image : images) {
                image.setUserMachineId(userMachine.getId());
            }
            userMachineImageMapper.insertBatchImage(images);
        }
        //判断是否有视频信息
        List<UserMachineVideo> videos = userMachineDTO.getVideos();
        if (videos != null && !videos.isEmpty()) {
            //插入视频信息
            for (UserMachineVideo video : videos) {
                video.setUserMachineId(userMachine.getId());
            }
            userMachineVideoMapper.insertBatchVideo(videos);
        }
        //插入完成后存入缓存，给管理端发送提醒处理信息
        String redisKey = "user_machine : upload:"+userMachine.getCreateUser();
        redisTemplate.opsForList().rightPush(redisKey, userMachine.getId());
        //插入完成后发送消息给管理端
        webSocketServer.sendToAllClient(1, userMachine.getId(), "用户上传"+userMachine.getName());
    }


    /**
     * 用户求购设备信息
     * @param userRequestMachineDTO
     */
    public void request(UserRequestMachineDTO userRequestMachineDTO) {
        UserRequestMachine userRequestMachine = new UserRequestMachine();
        BeanUtils.copyProperties(userRequestMachineDTO,userRequestMachine);
        userRequestMachine.setStatus(0);
        userRequestMachine.setCreateUser(BaseContext.getCurrentId());
        userRequestMachine.setCreateTime(LocalDateTime.now());
        userRequestMachineMapper.insert(userRequestMachine);

        //存入缓存
        String redisKey = "user_request_machine : request:"+userRequestMachine.getCreateUser();
        redisTemplate.opsForList().rightPush(redisKey, userRequestMachine.getId());
        //发送消息给管理端
        webSocketServer.sendToAllClient(2, userRequestMachine.getId(), "用户求购"+userRequestMachine.getName());
    }

    /**
     * 用户上传设备列表
     * @param status
     * @return
     */
    public List<UserMachineItemVO> list(Integer status) {
        Long userId = BaseContext.getCurrentId();
        List<UserMachineItemVO> userMachineItemVOList = userMachineMapper.list(status, userId);
        return userMachineItemVOList ;
    }

    /**
     * 用户求购设备列表
     * @param status
     * @return
     */
    public List<UserRequestMachineVO> listRequest(Integer status) {
        Long userId = BaseContext.getCurrentId();
        List<UserRequestMachineVO> userRequestMachineVOList = userRequestMachineMapper.listRequest(status, userId);
        return userRequestMachineVOList;
    }

    /**
     * 求购设备详情
     * @param id
     * @return
     */
    public UserRequestMachineDetailVO requestDetail(Long id) {
        UserRequestMachine userRequestMachine = userRequestMachineMapper.selectById(id);
        if (userRequestMachine != null) {
            // 安全获取处理人信息
            Employee employee = null;
            String handleUserName = null;
            if (userRequestMachine.getHandleUser() != null) {
                employee = employeeMapper.selectById(userRequestMachine.getHandleUser());
                handleUserName = (employee != null) ? employee.getName() : null;
            }

            // 安全获取创建用户信息
            User user = null;
            String createUserName = null;
            if (userRequestMachine.getCreateUser() != null) {
                user = userMapper.selectById(userRequestMachine.getCreateUser());
                createUserName = (user != null) ? user.getNickName() : null;
            }

            UserRequestMachineDetailVO userRequestMachineDetailVO = UserRequestMachineDetailVO.builder()
                    .id(userRequestMachine.getId())
                    .name(userRequestMachine.getName())
                    .machineSystem(userRequestMachine.getMachineSystem())
                    .brand(userRequestMachine.getBrand())
                    .categoryName(userRequestMachine.getCategoryName())
                    .year(userRequestMachine.getYear())
                    .quantity(userRequestMachine.getQuantity())
                    .price(userRequestMachine.getPrice())
                    .locationName(userRequestMachine.getLocationName())
                    .description(userRequestMachine.getDescription())
                    .phone(userRequestMachine.getPhone())
                    .status(userRequestMachine.getStatus())
                    .createTime(userRequestMachine.getCreateTime())
                    .handleTime(userRequestMachine.getHandleTime())
                    .createUser(createUserName)
                    .handleUser(handleUserName)
                    .build();

            return userRequestMachineDetailVO;
        }
        return null;
    }


    /**
     * 上传设备详情
     * @param id
     * @return
     */
    public UserMachineDetailVO uploadDetail(Long id) {
        UserMachine userMachine = userMachineMapper.selectById(id);
        if (userMachine != null) {
            // 查询该设备对应的图片列表
            List<UserMachineImage> images = userMachineImageMapper.selectList(
                    new QueryWrapper<UserMachineImage>().eq("user_machine_id", id));

            // 获取创建人用户信息
            User user = userMapper.selectById(userMachine.getCreateUser());

            // 获取处理人信息（有可能为空）
            Employee employee = null;
            String handleUser = null;
            if (userMachine.getHandleUser() != null) {
                employee = employeeMapper.selectById(userMachine.getHandleUser());
                handleUser = (employee != null) ? employee.getName() : null;
            }

            UserMachineDetailVO userMachineDetailVO = UserMachineDetailVO.builder()
                    .id(userMachine.getId())
                    .name(userMachine.getName())
                    .machineSystem(userMachine.getMachineSystem())
                    .brand(userMachine.getBrand())
                    .categoryName(userMachine.getCategoryName())
                    .year(userMachine.getYear())
                    .quantity(userMachine.getQuantity())
                    .price(userMachine.getPrice())
                    .locationName(userMachine.getLocationName())
                    .description(userMachine.getDescription())
                    .phone(userMachine.getPhone())
                    .status(userMachine.getStatus())
                    .createTime(userMachine.getCreateTime())
                    .handleTime(userMachine.getHandleTime())
                    .createUser(user != null ? user.getNickName() : null)
                    .handleUser(handleUser)
                    .images(images)
                    .build();

            return userMachineDetailVO;
        }
        return null;
    }


    /**
     * 用户上传设备分页查询
     * @param userMachinePageQueryDTO
     * @return
     */
    public PageResult uploadPage(UploadMachinePageQueryDTO userMachinePageQueryDTO) {
        PageHelper.startPage(userMachinePageQueryDTO.getPage(), userMachinePageQueryDTO.getPageSize());
        Page<UserMachineVO> page = userMachineMapper.uploadPageQuery(userMachinePageQueryDTO);
        long total = page.getTotal();
        List<UserMachineVO> records = page.getResult();
        return new PageResult(total, records);
    }


    /**
     * 修改用户上传设备状态
     * @param status
     * @param id
     */
    public void uploadStatus(Integer status, Long id) {
        // 构建更新对象
        UserMachine update = UserMachine.builder()
                .status(status)
                .handleTime(LocalDateTime.now())
                .handleUser(BaseContext.getCurrentId())
                .build();

        // 构建更新条件，只根据 id 更新
        QueryWrapper<UserMachine> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);

        // 执行更新
        userMachineMapper.update(update, queryWrapper);
        // 删除缓存
        UserMachine userMachine = userMachineMapper.selectById(id);
        if (userMachine != null){
            redisTemplate.opsForList()
                    .remove("user_machine : upload:"+userMachine.getCreateUser(), 1, userMachine.getId());
        }
    }

    /**
     * 批量删除用户上传设备
     * @param ids
     */
    public void deleteBatch(List<Long> ids) {
        // 删除缓存
        for (Long id : ids) {
            UserMachine userMachine = userMachineMapper.selectById(id);
            if (userMachine != null){
                redisTemplate.opsForList()
                        .remove("user_machine : upload:"+userMachine.getCreateUser(), 1, userMachine.getId());
            }
        }
        //删除Oss中的图片数据
        QueryWrapper<UserMachineImage> imageQuery = new QueryWrapper<>();
        imageQuery.in("user_machine_id", ids);
        List<UserMachineImage> images = userMachineImageMapper.selectList(imageQuery);
        if (!images.isEmpty()){
            List<String> imageObjectNames = images.stream()
                    .map(img -> aliOssUtil.extractObjectName(img.getImgUrl()))
                    .collect(Collectors.toList());
            aliOssUtil.deleteBatchOss(imageObjectNames);
        }
        //删除Oss中的视频数据
        QueryWrapper<UserMachineVideo> videoQuery = new QueryWrapper<>();
        videoQuery.in("user_machine_id", ids);
        List<UserMachineVideo> videos = userMachineVideoMapper.selectList(videoQuery);
        if (!videos.isEmpty()){
            List<String> videoObjectNames = videos.stream()
                    .map(video -> aliOssUtil.extractObjectName(video.getVideoUrl()))
                    .collect(Collectors.toList());
            aliOssUtil.deleteBatchOss(videoObjectNames);
        }
        userMachineMapper.deleteBatchIds(ids);
    }

    /**
     * 用户求购设备分页查询
     * @param requestMachinePageQueryDTO
     * @return
     */
    public PageResult requestPage(RequestMachinePageQueryDTO requestMachinePageQueryDTO) {
        PageHelper.startPage(requestMachinePageQueryDTO.getPage(), requestMachinePageQueryDTO.getPageSize());
        Page<UserRequestMachineVO> page = userRequestMachineMapper.requestPageQuery(requestMachinePageQueryDTO);
        long total = page.getTotal();
        List<UserRequestMachineVO> records = page.getResult();
        return new PageResult(total, records);
    }

    /**
     * 修改用户求购设备状态
     * @param status
     * @param id
     */
    public void requestStatus(Integer status, Long id) {
        // 构建更新对象
        UserRequestMachine update = UserRequestMachine.builder()
                .status(status)
                .handleTime(LocalDateTime.now())
                .handleUser(BaseContext.getCurrentId())
                .build();

        // 构建更新条件，只根据 id 更新
        QueryWrapper<UserRequestMachine> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);

        // 执行更新
        userRequestMachineMapper.update(update, queryWrapper);
        // 删除缓存
        UserRequestMachine userRequestMachine = userRequestMachineMapper.selectById(id);
        if (userRequestMachine != null){
            redisTemplate.opsForList()
                    .remove("user_request_machine : request:"+userRequestMachine.getCreateUser(), 1, userRequestMachine.getId());
        }
    }


    /**
     * 批量删除用户求购设备
     * @param ids
     */
    public void deleteRequestBatch(List<Long> ids) {
        //删除缓存
        for (Long id : ids) {
            UserRequestMachine userRequestMachine = userRequestMachineMapper.selectById(id);
            if (userRequestMachine != null){
                redisTemplate.opsForList()
                        .remove("user_request_machine : request:"+userRequestMachine.getCreateUser(), 1, userRequestMachine.getId());
            }
        }
        userRequestMachineMapper.deleteBatchIds(ids);
    }

}
